/*:
* @plugindesc (v1.04)對象二級訊息，按指定鍵或者點擊切換。
* @author cnda2010 & 老饕
* @version 1.0.4(nswda)
* @date 4/20/2019
*
* @param KeyCode Test Mode
* @text 鍵盤測試模式
* @type boolean
* @on 啟動
* @off 停用
* @desc 是否啟動鍵盤測試模式，此模式下鍵盤按鍵後會顯示該按鍵的編碼，為下面的參數提供標準。
* @default false
*
* @param Secondary KeyCode
* @text 切換顯示二級訊息按鍵編碼
* @type number
* @min 0
* @desc 切換二級顯示的鍵盤按鍵編碼，此編碼可通過鍵盤測試模式得到需要的結果。默認取112【鍵盤F1】
* @default 112
*
* @param Default Show Text
* @text 默認顯示二級訊息
* @type boolean
* @on 顯示二級訊息
* @off 顯示初始訊息
* @default true
*
* @param Space Length
* @text 符號空格長度
* @type number
* @default 0
* @desc 數值轉義符得到的數值中符號與數字之間的空格數量
*
* @param Need Change Scenes
* @text 允許切換的場景列表
* @type text[]
* @desc 允許切換的場景。
* @default ["Scene_Item","Scene_Skill","Scene_Equip","Scene_Battle","Scene_Shop"]
*
* @help
* 技能 物品 武器 裝備標籤
* <Secondary Text: text>
* 二級表述內容【固定】
* 表述內容支持轉義符
* \n：換行符
* 可以通過轉義符得到裝備的數據庫屬性。
* \hp：裝備的HP變化，帶符號
* \hpabs：裝備HP變化的絕對值
* \mp：裝備的MP變化，帶符號
* \mpabs：裝備MP變化的絕對值
* \atk：裝備攻擊力，帶符號
* \atkabs：裝備攻擊力絕對值
* \def：裝備防禦力，帶符號
* \defabs：裝備防禦力絕對值
* \mat：裝備魔法攻擊，帶符號
* \matabs：裝備魔法攻擊絕對	值
* \mdf：裝備魔法防禦，帶符號
* \mdfabs：裝備魔法防禦絕對值
* \agi：裝備敏捷，帶符號
* \agiabs：裝備敏捷絕對值
* \luk：裝備幸運，帶符號
* \lukabs：裝備幸運絕對值
* 在使用CP_TPCore時，有以下轉義符
* \tp：裝備TP變化（對應於<TP Plus: x>標籤的值），帶符號
* \tpabs：裝備TP變化的絕對值
* 
* 要顯示一個反斜槓【\】需要輸入4個反斜槓【\\\\】
* 上面所說的帶符號，即當結果是非負數時數字前會有【+】，數字的正負號與
* 值之間有若干空格，空格長度由插件參數決定，默認為1。
* 【例】<Secondary Text: 攻擊 \atk，魔攻 - \matabs。>
* 當物品攻擊力為1， 魔法攻擊為-2時會得到【攻擊 + 1，魔攻 - 2。】
*
* <Secondary Text Eval>
* //JavaScript code
* text = "攻擊 + 5  " + "防禦 + 5。";
* </Secondary Text Eval> 
*
* 更新日誌
* v1.00
* 插件完成
*
* v1.01
* 修復移動端點擊文字不變化的問題。
*
* v1.02
* 固定文字標籤支持轉義字符\n以及YEP訊息核心的部分轉義符
* 允許自由設定切換文字的鍵盤按鍵
*
* v1.03
* 增加轉義符讀取裝備的數據庫數據。
*
* v1.04
* 數據轉義符支持帶符號。
* 支持自定義帶符號數字中符號與數字之間的空格長度。
* 
* nswda
* 改為默認用「切換鍵（shift）」來切換說明。
*/

var Imported = Imported || {};
Imported.CP_ItemSecondaryInfo = true;

var params = PluginManager.parameters("CP_ItemSecondaryInfo");
var CP = CP || {};
CP.ItemInputManager = CP.ItemInputManager || {};

CP.ItemInputManager.KEY_KODE_TEST_MODE = eval(params["KeyCode Test Mode"]) || false;
CP.ItemInputManager.SECONDARY_KEY_KODE = Number(params["Secondary KeyCode"]) || 0;

CP.ItemInputManager.DEFAULT_SHOW_SECONDARY_TEXT = eval(params["Default Show Text"]);
CP.ItemInputManager.SPACE_LENGTH = Number(params["Space Length"]) || 0;
CP.ItemInputManager.NEED_CHANGE_SCENES = JSON.parse(params["Need Change Scenes"]);

for(var i = 0; i < CP.ItemInputManager.NEED_CHANGE_SCENES.length; i++){
	var string = CP.ItemInputManager.NEED_CHANGE_SCENES[i];
	CP.ItemInputManager.NEED_CHANGE_SCENES[i]= "scene instanceof " + string;
}

Input.keyMapper[CP.ItemInputManager.SECONDARY_KEY_KODE] = "F1";

CP.ItemInputManager.DATABASE_LOADED = DataManager.isDatabaseLoaded;
DataManager.isDatabaseLoaded = function(){
	if(!CP.ItemInputManager.DATABASE_LOADED.call(this))
		return false;

	CP.ItemInputManager.loadSecondaryData($dataSkills);
	CP.ItemInputManager.loadSecondaryData($dataItems);
	CP.ItemInputManager.loadSecondaryData($dataWeapons);
	CP.ItemInputManager.loadSecondaryData($dataArmors);

	return true;
};

CP.ItemInputManager.loadSecondaryData = function(dataArray){
	for(var i = 1; i < dataArray.length; i++){
		var item = dataArray[i];
		item.secondaryText = "";
		item.secondaryTextEval = null;
		if(item.meta["Secondary Text"]){
			var st = item.meta["Secondary Text"];
			item.secondaryText = st.trim();
		}

		if(item.meta["Secondary Text Eval"]){
			var reg = /<Secondary Text Eval>([\S\s]*)<\/Secondary Text Eval>/;
			reg.exec(item.note);
			item.secondaryTextEval = RegExp.$1;
		}
	}
};

CP.ItemInputManager.hasSecondaryText = function(item){
	if(!item)
		return false;
	if(!CP.ItemInputManager.getText(item))
		return false;
	return true;
};

CP.ItemInputManager.getText = function(item){
	var text = item.secondaryText || "";

	if(item.secondaryTextEval){
		try{
			eval(item.secondaryTextEval);
		}catch(e){
			console.log(e);
			text = item.secondaryText || "";
		}
	}

	if(text.trim() == "")
		text = null;

	return text;
};

CP.ItemInputManager.isNeedChangeText = function(){
	var scene = SceneManager._scene;
	for(var i = 0; i < CP.ItemInputManager.NEED_CHANGE_SCENES.length; i++){
		if(eval(CP.ItemInputManager.NEED_CHANGE_SCENES[i]))
			return true;
	}

	return false;
};

CP.ItemInputManager.getNumberString = function(value){
	if(typeof value !== "number")
		return value;
	var span = value < 0 ? "-" : "+";
	var space = "";
	for(var i = 0; i < this.SPACE_LENGTH; i++)
		space += " ";
	var number = String(Math.abs(value));

	return span + space + number;
};

//------------------------------
//  Input
//------------------------------
CP.ItemInputManager.ON_KEY_DOWN = Input._onKeyDown;
Input._onKeyDown = function(event){
	CP.ItemInputManager.ON_KEY_DOWN.call(this, event);

	if(CP.ItemInputManager.KEY_KODE_TEST_MODE)
		alert(event.keyCode);

	var name = Input.keyMapper[event.keyCode];
	//if(name === "F1")
	if(name === 'shift')
		this.onChangeShowText();
};

CP.ItemInputManager.UPDATE_GAMEPAD_STATE = Input._updateGamepadState;
Input._updateGamepadState = function(gamepad) {
	var lastState = this._gamepadStates[gamepad.index]|| [];
	CP.ItemInputManager.UPDATE_GAMEPAD_STATE.call(this, gamepad)
	var newState = this._gamepadStates[gamepad.index]
    for (var j = 0; j < newState.length; j++) {
        if (newState[j] !== lastState[j]) {
            var buttonName = this.gamepadMapper[j];
            if (buttonName) {
                this._currentState[buttonName] = newState[j];
				if(this._currentState['shift'])
					this.onChangeShowText();
            }
        }
    }
};
Input.onChangeShowText = function(){
	if(CP.ItemInputManager.isNeedChangeText())
		SceneManager._scene._helpWindow.onChangeShowText();
};

//------------------------------
//  Game_System
//------------------------------
CP.ItemInputManager.INIT_SYSTEM = Game_System.prototype.initialize;
Game_System.prototype.initialize = function(){
	CP.ItemInputManager.INIT_SYSTEM.call(this);

	this._showSecondaryData = CP.ItemInputManager.DEFAULT_SHOW_SECONDARY_TEXT;
};

Game_System.prototype.showSecondaryData = function(){
	if(!this._showSecondaryData)
		this._showSecondaryData = false;
	return this._showSecondaryData;
};

Game_System.prototype.setShowSecondaryData = function(show){
	this._showSecondaryData = show;
};

Game_System.prototype.changeShowSecondaryData = function(){
	this.setShowSecondaryData(!this.showSecondaryData());
};

//------------------------------
//  Window_Help
//------------------------------
CP.ItemInputManager.INIT_HELP_WINDOW = Window_Help.prototype.initialize;
Window_Help.prototype.initialize = function(numLines) {
    CP.ItemInputManager.INIT_HELP_WINDOW.call(this, numLines);

    this._item = null;
};

CP.ItemInputManager.SET_HELP_ITEM = Window_Help.prototype.setItem;
Window_Help.prototype.setItem = function(item) {
	CP.ItemInputManager.SET_HELP_ITEM.call(this, item);
	this._item = item;
	if(CP.ItemInputManager.hasSecondaryText(item) && (item.description.trim() === "" || $gameSystem.showSecondaryData())){
		var text = CP.ItemInputManager.getText(item);
		this.setText(this.convertEscapeCharactersForItemData(text, item));
	}
};

Window_Help.prototype.convertEscapeCharactersForItemData = function(text, item){
	text = this.addEnterCharacters(text);
	if(DataManager.isWeapon(item) || DataManager.isArmor(item))
		text = this.covertEquipDataCharacter(text, item);
	return Window_Base.prototype.convertEscapeCharacters.call(this, text);
};

Window_Help.prototype.addEnterCharacters = function(text){
	return text.replace(/\\n/g, "\n");
};

Window_Help.prototype.covertEquipDataCharacter = function(text, item){
	text = text.replace(/\\hpabs/g, this.paramHpAbs(item));
	text = text.replace(/\\hp/g, CP.ItemInputManager.getNumberString(this.paramHp(item)));
	text = text.replace(/\\mpabs/g, this.paramMpAbs(item));
	text = text.replace(/\\mp/g, CP.ItemInputManager.getNumberString(this.paramMp(item)));
	if(Imported.CP_TPCore){
		text = text.replace(/\\tpabs/g, this.paramTpAbs(item));
		text = text.replace(/\\tp/g, CP.ItemInputManager.getNumberString(this.paramTp(item))); 
	}
	text = text.replace(/\\atkabs/g, this.paramAtkAbs(item));
	text = text.replace(/\\atk/g, CP.ItemInputManager.getNumberString(this.paramAtk(item)));
	text = text.replace(/\\defabs/g, this.paramDefAbs(item));
	text = text.replace(/\\def/g, CP.ItemInputManager.getNumberString(this.paramDef(item)));
	text = text.replace(/\\matabs/g, this.paramMatAbs(item));
	text = text.replace(/\\mat/g, CP.ItemInputManager.getNumberString(this.paramMat(item)));
	text = text.replace(/\\mdfabs/g, this.paramMdfAbs(item));
	text = text.replace(/\\mdf/g, CP.ItemInputManager.getNumberString(this.paramMdf(item)));
	text = text.replace(/\\agiabs/g, this.paramAgiAbs(item));
	text = text.replace(/\\agi/g, CP.ItemInputManager.getNumberString(this.paramAgi(item)));
	text = text.replace(/\\lukabs/g, this.paramLukAbs(item));
	text = text.replace(/\\luk/g, CP.ItemInputManager.getNumberString(this.paramLuk(item)));
	return text;
};

Window_Help.prototype.paramValue = function(item, index){
	if(!item)
		return 0;
	return item.params[index];
};

Window_Help.prototype.paramHp = function(item){
	return this.paramValue(item, 0);
};

Window_Help.prototype.paramHpAbs = function(item){
	return Math.abs(this.paramHp(item));
};

Window_Help.prototype.paramMp = function(item){
	return this.paramValue(item, 1);
};

Window_Help.prototype.paramMpAbs = function(item){
	return Math.abs(this.paramMp(item));
};

Window_Help.prototype.paramTp = function(item){
	if(!item)
		return 0;
	return item.tpPlus;
};

Window_Help.prototype.paramTpAbs = function(item){
	return Math.abs(this.paramTp(item));
};

Window_Help.prototype.paramAtk = function(item){
	return this.paramValue(item, 2);
};

Window_Help.prototype.paramAtkAbs = function(item){
	return Math.abs(this.paramAtk(item));
};

Window_Help.prototype.paramDef = function(item){
	return this.paramValue(item, 3);
};

Window_Help.prototype.paramDefAbs = function(item){
	return Math.abs(this.paramDef(item));
};

Window_Help.prototype.paramMat = function(item){
	return this.paramValue(item, 4);
};

Window_Help.prototype.paramMatAbs = function(item){
	return Math.abs(this.paramMat(item));
};

Window_Help.prototype.paramMdf = function(item){
	return this.paramValue(item, 5);
};

Window_Help.prototype.paramMdfAbs = function(item){
	return Math.abs(this.paramMdf(item));
};

Window_Help.prototype.paramAgi = function(item){
	return this.paramValue(item, 6);
};

Window_Help.prototype.paramAgiAbs = function(item){
	return Math.abs(this.paramAgi(item));
};

Window_Help.prototype.paramLuk = function(item){
	return this.paramValue(item, 7);
};

Window_Help.prototype.paramLukAbs = function(item){
	return Math.abs(this.paramLuk(item));
};

Window_Help.prototype.isTouchedInsideFrame = function() {
    var x = this.canvasToLocalX(TouchInput.x);
    var y = this.canvasToLocalY(TouchInput.y);
    return x >= 0 && y >= 0 && x < this.width && y < this.height;
};

Window_Help.prototype.onTouch = function(){
	this.onChangeShowText();
};

Window_Help.prototype.onChangeShowText = function(){
	$gameSystem.changeShowSecondaryData();
	this.setItem(this._item);
	this.refresh();
};

Window_Help.prototype.processTouch = function() {
    if (this.isOpen() && CP.ItemInputManager.isNeedChangeText()) {
        if (TouchInput.isTriggered() && this.isTouchedInsideFrame()) {
            this.onTouch();
        }
    }
};

Window_Help.prototype.update = function(){
	Window_Base.prototype.update.call(this);

	this.processTouch();
};